<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix header-box">
        <span>商家管理</span>
        <el-input placeholder="请输入内容" v-model="inputName" style="width: 300px;" class="input-with-select">
          <el-button slot="append" icon="el-icon-search" @click="search(true)"></el-button>
        </el-input>
      </div>
      <div style="min-width: 1200px;">
        <el-table  stripe :data="tableData.slice((currentPage4 - 1) * pageSize, currentPage4 * pageSize)" style="width: 100%">
          <el-table-column prop="id" label="id"   align="center"/>
          <el-table-column prop="trade_name" label="店名"  align="center" />
          <el-table-column prop="trade_address" label="地址"  align="center" />
          <el-table-column prop="linkman" label="联系人"  align="center" />
          <el-table-column prop="tel" label="联系方式"   align="center"/>
          <el-table-column prop="email" label="邮箱"  align="center"/>
          <el-table-column prop="date" label="创建时间" width="220"  align="center" />
          <el-table-column label="操作" width="220" align="center"> 
            <template slot-scope="scope">
              <el-button type="primary" size="min" icon="el-icon-plus" @click="addMerchantFn"></el-button>
              <el-button type="primary" size="min" icon="el-icon-edit" @click="updateFn(scope.row)"></el-button>
              <el-button type="primary" size="min" icon="el-icon-delete" @click="removeFn(scope.row.id)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="currentPage4" :page-sizes="[3, 5, 7, 10]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加分类的对话框 -->
    <el-dialog :title="isEdit ? '编辑商家数据' : '添加商家数据'" :visible.sync="addVisible" width="35%">
      <el-form :model="addForm" :rules="addRules" ref="addRef" label-width="80px">
        <el-form-item label="店名" prop="trade_name">
          <el-input v-model="addForm.trade_name" minlength="1" maxlength="10"></el-input>
        </el-form-item>

        <el-form-item label="地址" prop="trade_address">
          <el-input v-model="addForm.trade_address" minlength="1" maxlength="10"></el-input>
        </el-form-item>

        <el-form-item label="联系人" prop="linkman">
          <el-input v-model="addForm.linkman" minlength="1" maxlength="10"></el-input>
        </el-form-item>

        <el-form-item label="联系电话" prop="tel">
          <el-input v-model="addForm.tel" minlength="1" maxlength="11"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" minlength="1" maxlength="20"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="cancelFn">取 消</el-button>
        <el-button size="mini" type="primary" @click="addFn">添 加</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getMerchantAPI, addMerchantAPI, updateMerchantAPI,delMerchantAPI } from '@/api/merchant'
export default {
  data() {
    return {
      tableData: [],
      inputName: '',
      currentPage4: 1,
      pageSize: 10,
      total: 20,
      addVisible: false,
      editId: '',
      isEdit: false,
      addForm: {
        trade_name: '',
        trade_address: '',
        linkman: '',
        tel: '',
        email: ''
      },
      addRules: {
        trade_name: [
          { required: true, message: '请输入店铺名称', trigger: 'blur' },
          { pattern: /^\S{1,10}$/, message: '店铺名称必须是1-10位的非空字符', trigger: 'blur' }
        ],
        trade_address: [
          { required: true, message: '请输入店铺地址', trigger: 'blur' },
          { pattern: /^\S{1,10}$/, message: '店铺地址必须是1-10位的非空字符', trigger: 'blur' }
        ],
        linkman: [
          { required: true, message: '请输入联系人', trigger: 'blur' },
          { pattern: /^\S{1,10}$/, message: '联系人必须是1-10位的非空字符', trigger: 'blur' }
        ],
        tel: [
          { required: true, message: '请输入联系人电话', trigger: 'blur' },
          { pattern: /^\S{1,11}$/, message: '联系人电话必须是1-11位的非空字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: '邮箱必须是1-20位的非空字符', trigger: 'blur' }
        ],
      }
    }
  },
  methods: {

    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = 1
      this.pageSize = val
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage4 = val
    },
    search(bool) {
      if (bool) {
        let newListData = []
        if (this.inputName) {
          this.tableData.filter((item) => {
            if (item.trade_name.indexOf(this.inputName) !== -1) {
              newListData.push(item)
            }
          });
        }
        this.tableData = newListData;
      } else {
        window.location.reload();
      }
    },
    async initGetMerchantFn() {
      const res = await getMerchantAPI()
      if (res.status !== 200) {
        this.$message.error('获取数据失败!')
      } else {
        this.$message.success('获取数据成功!')
        this.tableData = res.data.data
        this.total = res.data.total
      }
    },
    // 添加按钮事件回调
    addMerchantFn() {
      this.addVisible = true
      this.$refs.addRef.resetFields()
    },
    // 对话框取消按钮事件回调
    cancelFn() {
      this.addVisible = false
      this.editId = ''
      this.isEdit = false
      this.$refs.addRef.resetFields()
    },
    // 对话框添加按钮事件回调
    async addFn() {
      this.$refs.addRef.validate(async valid => {
        if (valid) {
          if (this.isEdit) {
            const { data: res } = await updateMerchantAPI({ id: this.editId, ...this.addForm })
            if (res.status !== 0) {
              this.$message.error('修改数据失败！')
            } else {
              this.$message.success('修改数据成功！')
            }
          } else {
            const { data: res } = await addMerchantAPI(this.addForm)
            if (res.status !== 0) {
              this.$message.error('添加数据失败！')
            } else {
              this.$message.success('添加数据成功！')
            }
          }
          this.initGetMerchantFn()
          this.addVisible = false
          this.$refs.addRef.resetFields()
        }
      })
    },
    // 修改按钮事件回调
    updateFn(obj) {
      this.editId = obj.id
      this.isEdit = true
      this.addVisible = true
      this.$nextTick(() => {
        this.addForm.trade_name = obj.trade_name
        this.addForm.trade_address = obj.trade_address
        this.addForm.linkman = obj.linkman
        this.addForm.tel = obj.tel
        this.addForm.email = obj.email
      })
    },
    // 删除按钮事件回调
    async removeFn(id){
      const {data:res} = await delMerchantAPI(id)
      if(res.status !== 0){
        this.$message.error('删除数据失败！')
      }else{
        this.$message.success('删除数据成功！')
        this.initGetMerchantFn()
      }
    }
  },
  watch: {
    inputName(newValue) {
      if (newValue) {
        this.search(true)
      } else {
        this.search(false)
      }
    }
  },
  created() {
    this.initGetMerchantFn()
  }
}
</script>

<style scoped>
.header-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  display: flex;
  justify-content: center;
  margin: 10px;
}
</style>
